﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Text;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.ServiceHosting.ServiceRuntime;

namespace UlyssesAgenda.Storage.Table
{
    public static class GameTableStorage
    {
        private static StorageAccountInfo tableStorageAccount = null;

        static GameTableStorage()
        {
            tableStorageAccount = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();
        }

        public static IEnumerable<BlogEntry> GetBlogEntries(TableStorage tableStorage, int pageSize, int page)
        {
            TableStorageDataServiceContext svc = tableStorage.GetDataServiceContext();

            IEnumerable<BlogEntry> query = from c in svc.CreateQuery<BlogEntry>(RoleManager.GetConfigurationSetting("BlogEntryTableName"))
                                           //orderby c.CreateDateTime descending
                                           select c;

            return QueryTable(tableStorage, query, pageSize, page);
        }

        public static void InsertBlogEntry(TableStorage tableStorage, string title, string author, string canonicalName)
        {
            TableStorageDataServiceContext svc = tableStorage.GetDataServiceContext();

            BlogEntry entry = new BlogEntry();
            entry.PartitionKey = author;
            entry.RowKey = title;
            entry.Title = title;
            entry.Author = author;
            entry.CreateDateTime = DateTime.Now;
            entry.CanonicalName = canonicalName;

            svc.AddObject(RoleManager.GetConfigurationSetting("BlogEntryTableName"), entry);
            svc.SaveChanges();
        }

        private static IEnumerable<T> QueryTable<T>(TableStorage tableStorage, IEnumerable<T> query, int pageSize, int page) where T : TableStorageEntity
        {
            TableStorageDataServiceQuery<T> q = new TableStorageDataServiceQuery<T>(query as DataServiceQuery<T>);
            IEnumerable<T> rows = q.ExecuteAllWithRetries();

            return rows.Skip((page - 1) * pageSize).Take(pageSize);
        }
    }
}